package pattern.singleton.demo7;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @Author suzhengzhuang
 * @Email: suzhengzhuang@icloud.com
 * @Date 2024/4/17 10:08
 * @PackageName:pattern.singleton.demo1
 * @ClassName: Client
 * @Description: TODO 通过序列化与反序列化破坏单例模式
 * @Version 1.0
 */
public class Client {

    public static void main(String[] args) throws Exception {

        writeObject();
        /**
         * 读取两次文件中的对象,发现地址不同，破坏单例模式
         * pattern.singleton.demo7.Singleton@735f7ae5
         * pattern.singleton.demo7.Singleton@180bc464
         * */
        readObject();
        readObject();
    }

    // 向文件中写对象
    public static void writeObject() throws Exception{
        //1.获取Singleton对象
        Singleton instance = Singleton.getInstance();
        //2.创建对象输出流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
        //3.写对象
        oos.writeObject(instance);
        //4.释放资源
        oos.close();
    }

    // 从文件读取对象
    public static void readObject() throws Exception{

        // 获取对象输入流
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"));
        // 读取对象
        Singleton instance = (Singleton) ois.readObject();
        System.out.println(instance);
        // 释放资源
        ois.close();
    }
}
